<template>
  <div>
    <div class="score-manage-search">
      <Button @click="openScoreModal()">加减分</Button>
      <Select filterable
        v-model="scoreSearch.type"
        filterable
        clearable
        transfer
        placeholder="请选择加减分类型"
        @on-change="getScoreManageList(1)"
      >
        <Option :value="2" title="加分">加分</Option>
        <Option :value="1" title="减分">减分</Option>
      </Select>
      <Select filterable
        v-model="scoreSearch.company"
        filterable
        clearable
        transfer
        placeholder="请选择单位"
        @on-change="getScoreManageList(1)"
      >
        <Option v-for="item in companyList" :value="item" :key="item" :title="item">{{
          item
        }}</Option>
      </Select>
      <Select filterable
        v-model="scoreSearch.groupId"
        filterable
        clearable
        transfer
        placeholder="请选择团队"
        @on-change="getScoreManageList(1)"
      >
        <Option v-for="item in allTeamList" :value="item.id" :key="item.id" :title="item.name">{{
          item.name
        }}</Option>
      </Select>
      <Button @click="resetSearch"><i class="el-icon-refresh-right"/></Button>
    </div>
    <Table border :columns="scoreCol" :data="scoreManageList"></Table>
    <div style="display: flex;justify-content: center;margin: 15px 0">
      <Page
        :total="scoreTotal"
        @on-change="getScoreManageList"
        show-elevator
        show-total
        :current="scoreSearch.page"
      />
    </div>
    <Modal v-model="showScoreModal" @on-visible-change="visibleChange" title="加减分">
      <Form ref="scoreModal" :model="scoreManageObj" :rules="scoreModalRules" :label-width="100">
        <FormItem label="操作对象" prop="targetType">
          <RadioGroup
            v-model="scoreManageObj.targetType"
            @on-change="
              scoreManageObj.groupId = '';
              scoreManageObj.company = '';
            "
          >
            <Radio :label="0" :disabled="scoreManageObj.activeType === 'update'">
              <span>单位</span>
            </Radio>
            <Radio :label="1" :disabled="scoreManageObj.activeType === 'update'">
              <span>团队</span>
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="单位" v-if="scoreManageObj.targetType === 0" prop="company" key="company">
          <Select filterable
            v-model="scoreManageObj.company"
            :disabled="scoreManageObj.activeType === 'update'"
            filterable
            clearable
            transfer
            placeholder=""
          >
            <Option v-for="item in companyList" :value="item" :key="item" :title="item">{{
              item
            }}</Option>
          </Select>
        </FormItem>
        <FormItem label="团队" v-else prop="groupId" key="group">
          <Select filterable
            v-model="scoreManageObj.groupId"
            :disabled="scoreManageObj.activeType === 'update'"
            filterable
            clearable
            transfer
            placeholder=""
          >
            <Option v-for="item in teamList" :value="item.id" :key="item.id" :title="item.name">{{
              item.name
            }}</Option>
          </Select>
        </FormItem>
        <FormItem label="加减分类型" prop="type">
          <RadioGroup v-model="scoreManageObj.type">
            <Radio :label="2">
              <span>加分</span>
            </Radio>
            <Radio :label="1">
              <span>减分</span>
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="分值" prop="score">
          <Input v-model="scoreManageObj.score" number></Input>
        </FormItem>
        <FormItem :label="`${scoreManageObj.type === 2 ? '加分' : '减分'}原因`" prop="approvalInfo">
          <Input
            v-model="scoreManageObj.approvalInfo"
            :maxlength="200"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 5 }"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer" class="footer">
        <Button type="text" size="large" @click="showScoreModal = false">取消</Button>
        <Button
          type="primary"
          size="large"
          @click="saveScoreManage"
          :loading="scoreManageObj.loading"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  getScoreManageList,
  addScoreManage,
  updateScoreManage,
  deleteScoreManage,
  getAlarmList
} from '@/api/referee.js';
import { getTopoTargetList, getDeclareCompanyList } from '@/api/drill_compete';
import { getaccessgrouplist } from '@/api/access_new';
export default {
  name: 'scoreManage',
  props: ['projectId', 'sceneId'],
  data() {
    return {
      showScoreModal: false,
      scoreTotal: 0,
      targetList: [],
      teamList: [],
      allTeamList: [], // 包含管理员团队组
      scoreSearch: {
        page: 1,
        pageSize: 10,
        type: '',
        groupId: '',
        target: ''
      },
      scoreManageObj: {
        // 添加、修改加减分的数据
        targetType: 0, // 0目标  1团队
        approvalInfo: '',
        company: '',
        groupId: '',
        target: '',
        score: '',
        type: 1,
        loading: false,
        activeType: 'add' // 区别是添加操作还是修改操作
      },
      scoreManageList: [],
      scoreManageModel: false,
      scoreCol: [
        {
          title: '单位',
          key: 'company',
          width: 138,
          tooltip: true
        },
        {
          title: '团队',
          key: 'groupName',
          width: 138,
          tooltip: true
        },
        {
          title: '操作类型',
          key: 'type',
          width: 138,
          tooltip: true,
          render: (h, params) => {
            return h('span', params.row.type === 2 ? '加分' : '减分');
          }
        },
        {
          title: '分值',
          key: 'score',
          width: 138,
          tooltip: true
        },
        {
          title: '创建者',
          key: 'creatorName',
          width: 138,
          tooltip: true
        },
        {
          title: '原因',
          key: 'approvalInfo',
          width: 138,
          tooltip: true
        },
        {
          title: '操作',
          key: 'active',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.showScoreModal = true;
                      this.scoreManageObj = Object.assign(
                        {
                          targetType: params.row.company ? 0 : 1, // 0目标  1团队
                          loading: false,
                          activeType: 'update'
                        },
                        params.row
                      );
                    }
                  }
                },
                '修改'
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    'ok-text': '确定',
                    'cancel-text': '取消',
                    type: 'error',
                    size: 'large',
                    title: '你确定要删除吗?',
                    transfer: true
                  },
                  on: {
                    'on-ok': () => {
                      this.deleteScoreManage(params.row.id);
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'error',
                        size: 'small'
                      },
                      style: {
                        marginRight: '5px'
                      }
                    },
                    '删除'
                  )
                ]
              )
            ]);
          }
        }
      ],
      companyList: []
    };
  },
  created() {
    this.getTargetList();
    this.getDeclareCompanyList();
    this.getScoreManageList();
  },
  methods: {
    // 获取加减分列表
    getScoreManageList(page) {
      if (page) {
        this.scoreSearch.page = page;
      }
      getScoreManageList(Object.assign(this.scoreSearch, { testId: this.sceneId }))
        .then(({ data = {} }) => {
          let { code, message } = data;
          data = data.data || {};
          if (code !== 1) {
            this.$Message.warning(message);
            return;
          }
          this.scoreTotal = data.totalCount || 0;
          this.scoreManageList = data.pageData || [];
        })
        .catch(() => {
          this.$Message.error('获取加减分列表异常');
        });
    },
    // 创建或修改数据
    saveScoreManage() {
      this.$refs.scoreModal.validate((valid) => {
        if (valid) {
          this.scoreManageObj.loading = true;
          let { id, name, projectid, projectname } = this.currentTemplate;
          let data = Object.assign(this.scoreManageObj, {
            // 操作团队时查询团队名称，否则设置为undefined
            groupName:
              this.scoreManageObj.targetType === 1
                ? this.getOptionName(this.scoreManageObj.groupId, this.scoreManageObj.targetType)
                : undefined,
            // 操作目标时查询目标名称，否则设置为undefined
            company: this.scoreManageObj.targetType === 0 ? this.scoreManageObj.company : '',
            projectId: projectid,
            projectName: projectname,
            testId: id,
            testName: name
          });
          if (this.scoreManageObj.targetType === 0) {
            // 针对目标加减分，需要补全团队Id、团队名称
            data.groupId = this.adminTeam.id;
            data.groupName = this.adminTeam.name;
          }
          let api = this.scoreManageObj.activeType === 'add' ? addScoreManage : updateScoreManage;
          let text = this.scoreManageObj.activeType === 'add' ? '添加' : '修改';
          api(data)
            .then(({ data = {} }) => {
              let { code, message } = data;
              if (code !== 1) {
                this.$Message.warning(message);
                return;
              }
              this.$Message.info(`${text}加减分成功`);
              this.scoreManageObj.activeType === 'add'
                ? this.resetSearch()
                : this.getScoreManageList();
              this.showScoreModal = false;
            })
            .catch(() => {
              this.$Message.error(`${text}加减分异常`);
            })
            .finally(() => {
              this.scoreManageObj.loading = false;
            });
        }
      });
    },
    // 删除加减分
    deleteScoreManage(id) {
      deleteScoreManage(id)
        .then(({ data = {} }) => {
          let { code, message } = data;
          if (code !== 1) {
            this.$Message.warning(message);
            return;
          }
          this.$Message.info('删除成功');
          if (this.scoreManageList.length === 1 && this.scoreSearch.page > 1) {
            this.scoreSearch.page--;
          }
          this.getScoreManageList();
        })
        .catch(() => {
          this.$Message.error('删除加减分异常');
        });
    },
    getDeclareCompanyList() {
      getDeclareCompanyList(this.projectid)
        .then(({ code, data, message }) => {
          if (code === 1) {
            this.companyList = data;
          } else {
          }
        })
        .catch((error) => {});
    },
    // 攻击方获取团队的数据，防守方获取靶标的数据，并综合为统一的数组用于使用
    getTargetList() {
      let { id, projectid } = this.currentTemplate;
      Promise.all([
        getTopoTargetList({
          ageIndex: 1,
          pageSize: 2147483646,
          projectId: this.projectId
        }),
        getaccessgrouplist({
          pageIndex: 1,
          pageSize: 2147483646,
          testId: this.sceneId
        })
      ])
        .then((res) => {
          if (res.some((item) => item.code !== 1)) {
            this.$Message.warning('获取团队、目标列表有误');
          }
          res.forEach((item, index) => {
            if (item.code === 1) {
              if (index === 0) {
                // 查询的是靶标
                this.targetList = (item.data && item.data.items) || [];
              } else {
                let list = (item.data && item.data.items) || [];
                this.adminTeam = list.find((item) => item.creatorName === '内部服务用户') || {};
                this.teamList = list.filter((item) => item.creatorName !== '内部服务用户') || [];
                this.allTeamList = list;
              }
            }
          });
        })
        .catch(() => {
          this.$Message.error('获取团队、目标列表异常');
        });
    }
  }
};
</script>
